/* --------------------------------------------------------
 * Copyright (c) aeky , Inc.  All rights reserved.
 * --------------------------------------------------------
 */
package com.aeky.server.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.aeky.exception.SessionLostException;
import com.aeky.model.User;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RPCServletUtils;

/**
 * 自定义拦截器(检查Session是否有效)
 * 
 * @author aeky
 */
public class SessionCheckInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(SessionCheckInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOG.info("into SessionCheckInterceptor preHandle()");
        String uri = request.getRequestURI();
        LOG.info(" request url is {} " + uri);
        if (uri.indexOf("rpc/login") > 0) {
            return Boolean.TRUE;
        }
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            LOG.info("session user is null");
            String requestPayload = RPCServletUtils.readContentAsGwtRpc(request);
            LOG.info("the request payload is {}", requestPayload);
            RPCRequest rpcRequest = RPC.decodeRequest(requestPayload, null);
            String failurePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), new SessionLostException(),
                    rpcRequest.getSerializationPolicy());
            LOG.info("the failure payload is {}", failurePayload);
            byte[] responseBytes = failurePayload.getBytes("UTF-8");
            response.setContentLength(responseBytes.length);
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(200);
            response.setHeader("Content-Disposition", "attachment");
            response.getOutputStream().write(responseBytes);
            return Boolean.FALSE;
        } else {
            LOG.info(" user is {}", user.getLoginName());
            return Boolean.TRUE;
        }
    }
}
